package cn.ffcs.uec.outStaffBatchImportApply.action;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Messagebox;

import cn.ffcs.raptornuke.plugin.common.zk.ctrl.BasePortletComposer;
import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.raptornuke.portal.theme.ThemeDisplay;
import cn.ffcs.uec.common.util.NodeVoUtil;
import cn.ffcs.uec.common.util.UecConstants;
import cn.ffcs.uec.organization.manager.UecOrgOrgsManager;
import cn.ffcs.uec.organization.model.UecOrgOrgs;
import cn.ffcs.uec.outStaff.manager.UecOutStaffManager;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.outStaffBatchImportApply.action.bean.OutStaffEncApprovalViewMainBean;
import cn.ffcs.uec.recordsApproval.constant.ApprovalConstants;
import cn.ffcs.uec.recordsApproval.util.ApprovalUtil;
import cn.ffcs.uec.staff.manager.UecEncManager;
import cn.ffcs.uec.staff.model.UecEnc;
import cn.ffcs.uec.staffRecords.vo.AtiOaBaseObject;
import cn.ffcs.uom.common.model.DefaultDaoFactory;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.PubUtil;
import cn.ffcs.uom.common.util.StrUtil;

@Controller
@Scope("prototype")
public class OutStaffEncApprovalViewMainComposer extends BasePortletComposer {

	private static final long serialVersionUID = -5177954236734589121L;

	private OutStaffEncApprovalViewMainBean bean = new OutStaffEncApprovalViewMainBean();

	private UecOutStaffManager uecOutStaffManager = (UecOutStaffManager) ApplicationContextUtil
			.getBean("uecOutStaffManager");

	private UecEncManager uecEncManager = (UecEncManager) ApplicationContextUtil
			.getBean("uecEncManager");

	private UecOrgOrgsManager uecOrgOrgsManager = (UecOrgOrgsManager) ApplicationContextUtil
			.getBean("uecOrgOrgsManager");

	/**
	 * 外包人员基本信息
	 */
	private UecOutStaffInfo outStaffInfo = UecOutStaffInfo.newInstance();

	private UecEnc uecEnc = UecEnc.newInstance();

	private String taskDefKey;

	private String opType;

	private String taskId;

	private AtiOaBaseObject oaBaseObject;

	@Override
	public String getPortletId() {
		return super.getPortletId();
	}

	@Override
	public ThemeDisplay getThemeDisplay() {
		return super.getThemeDisplay();
	}

	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		Components.wireVariables(comp, bean);

	}

	/**
	 * 界面初始化
	 */
	public void onCreate$outStaffEncApprovalViewMainWin() {
		bandListbox();
		bindBean();
	}

	/**
	 * 重新申请
	 * 
	 * @throws InterruptedException
	 */
	public void onOk() throws InterruptedException {
		// 非查看历史工单
		if (!ApprovalConstants.OP_TYPE_VIEW.equals(opType)) {
			// 判断任务是否已被处理
			boolean isCompleted = ApprovalUtil.isTaskCompleted(oaBaseObject,
					taskId);
			if (isCompleted) {
				onCancel();
				Events.postEvent(ApprovalConstants.ON_REFRESH_QUERY_RESPONSE,
						this.self, null);
				ZkUtil.showError("任务不存在或已被处理完毕！", "错误提示");
				return;
			}
			// 校验
			String msg = this.checkUacStaffData();
			if (null != msg) {
				Messagebox.show(msg);
				return;
			}
			Messagebox.show("是否提交审批？", "输入确认提示", Messagebox.OK
					| Messagebox.CANCEL, Messagebox.QUESTION,
					new EventListener() {
						@Override
						public void onEvent(Event event) throws Exception {
							if (((Integer) event.getData()).intValue() == Messagebox.OK) {
								postApprovalData();
								onCancel();
							} else {
								return;
							}
						}
					});
		} else {
			this.onCancel();
		}

	}

	public void postApprovalData() throws InterruptedException {
		String currentName = ApprovalUtil.getCurrentName();
		if (StrUtil.isNullOrEmpty(currentName)) {
			ZkUtil.showError("当前登录用户已失效，请重新登录!", "错误提示");
			return;
		}

		PubUtil.fillPoFromEditorBean(uecEnc, bean);
		uecEnc.setEncourdate(DateUtil
				.dateToStr(bean.getEncourdate().getValue()));
		uecEnc.setModifiedtime(DateUtil.getCurrenDate());
		uecEnc.setModifier(currentName);
		DefaultDaoFactory.getDefaultDao().updateObject(uecEnc);

		Events.postEvent("onOKResponse", this.self,
				ApprovalConstants.ON_OK_RESULT);

	}

	/**
	 * 审批同意
	 * 
	 * @throws InterruptedException
	 */
	public void onApproval() throws InterruptedException {
		Messagebox.show("是否提交审批？", "输入确认提示", Messagebox.OK | Messagebox.CANCEL,
				Messagebox.QUESTION, new EventListener() {
					@Override
					public void onEvent(Event event) throws Exception {
						if (((Integer) event.getData()).intValue() == Messagebox.OK) {
							approvalData();
						} else {
							return;
						}
					}
				});
	}

	public void approvalData() {
		Map<String, Object> map = new HashMap<String, Object>();
		String comment = this.getComment(taskDefKey);
		map.put("comment", comment);
		map.put("onApprovalResult", ApprovalConstants.ON_APPROVAL_RESULT);
		Events.postEvent("onApprovalResponse", this.self, map);
		this.onCancel();

	}

	/**
	 * 审批拒绝
	 */
	public void onReject() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("comment", this.getComment(taskDefKey));
		map.put("onRejectResult", ApprovalConstants.ON_REJECT_RESULT);
		Events.postEvent("onRejectResponse", this.self, map);
		this.onCancel();
	}

	/**
	 * 关闭弹窗
	 */
	public void onCancel() {
		this.bean.getOutStaffEncApprovalViewMainWin().onClose();
	}

	/**
	 * 获取传值
	 * 
	 * @throws ParseException
	 * @throws WrongValueException
	 */
	private void bindBean() {
		String procDefName = (String) arg.get("procDefName");
		this.bean.getOutStaffEncApprovalViewMainWin().setTitle(
				procDefName + "审批");

		oaBaseObject = (AtiOaBaseObject) arg.get("oaBaseObject");
		if (!StrUtil.isNullOrEmpty(oaBaseObject)) {
			// 获取审批意见
			PubUtil.fillBeanFromPo(oaBaseObject, bean);
		}
		opType = (String) arg.get("opType");
		if (ApprovalConstants.OP_TYPE_VIEW.equals(opType)) {
			// 查看历史工单
			setButtonValid(true, false, false);
			setTextValid(true, true, true);
		} else {

			taskDefKey = (String) arg.get("taskDefKey");
			if ("modify".equals(taskDefKey)) {
				setButtonValid(true, false, false);
				setTextValid(false, false, false);
			} else {
				setButtonValid(false, true, true);
			}
			if ("deptLeaderAudit".equals(taskDefKey)) {
				this.bean.getSecondText().setRows(2);
				this.setTextValid(true, false, false);
				bean.getSecondText().setValue(null);
			}
			if ("hrAudit".equals(taskDefKey)) {
				this.bean.getThirdText().setRows(2);
				this.setTextValid(false, true, false);
				bean.getThirdText().setValue(null);
			}
			if ("hrLeaderAudit".equals(taskDefKey)) {
				this.bean.getFourthText().setRows(2);
				this.setTextValid(false, false, true);
				bean.getFourthText().setValue(null);
			}
		}

		taskId = (String) arg.get("taskId");
		if (null != oaBaseObject) {
			// 2.获取人员信息
			String outStaffIdHis = oaBaseObject.getOutStaffIdHis();
			outStaffInfo.setOutStaffId(Long.parseLong(outStaffIdHis));
			outStaffInfo = uecOutStaffManager
					.findUecOutStaffInfoByOutStaffId(outStaffInfo);
			if (null != outStaffInfo) {
				PubUtil.fillBeanFromPo(outStaffInfo, bean);
				UecOrgOrgs newOrgOrgs = UecOrgOrgs.newInstance();
				newOrgOrgs.setPkOrg(outStaffInfo.getPkHrorg());
				newOrgOrgs = uecOrgOrgsManager
						.findUecOrgOrgsByUecOrgOrgs(newOrgOrgs);
				if (null != newOrgOrgs) {
					bean.getUecOrgOrgsBandboxExt().setValue(
							newOrgOrgs.getName());
				}
			}
			// 获取审批中人员奖励信息
			String encId = oaBaseObject.getEncId();
			uecEnc.setEncId(Long.valueOf(encId));
			uecEnc = uecEncManager.findUecEncById(uecEnc);
			PubUtil.fillBeanFromPo(uecEnc, bean);
			bean.getEncourdate().setValue(
					DateUtil.patternStrToDate(uecEnc.getEncourdate()));
		}

	}

	/**
	 * 获取审批意见
	 * 
	 * @param taskDefKey
	 * @return
	 */
	private String getComment(String taskDefKey) {
		if ("deptLeaderAudit".equals(taskDefKey)) {
			return this.bean.getSecondText().getValue();
		}
		if ("hrAudit".equals(taskDefKey)) {
			return this.bean.getThirdText().getValue();
		}
		if ("hrLeaderAudit".equals(taskDefKey)) {
			return this.bean.getFourthText().getValue();
		}
		return null;
	}

	/**
	 * 设置按钮
	 * 
	 * @param canEdit
	 * @param canApproval
	 * @param canReject
	 */
	private void setButtonValid(boolean canEdit, boolean canApproval,
			boolean canReject) {
		this.bean.getOkBtn().setVisible(canEdit);
		this.bean.getOkBtn().setDisabled(!canEdit);

		this.bean.getApprovalBtn().setVisible(canApproval);
		this.bean.getApprovalBtn().setDisabled(!canApproval);

		this.bean.getRejectBtn().setVisible(canReject);
		this.bean.getRejectBtn().setDisabled(!canReject);

	}

	/**
	 * 设置审批意见栏
	 * 
	 * @param secondCanEdit
	 * @param thirdCanEdit
	 * @param fourthCanEdit
	 */
	private void setTextValid(boolean secondCanEdit, boolean thirdCanEdit,
			boolean fourthCanEdit) {
		this.bean.getSecondText().setDisabled(!secondCanEdit);
		this.bean.getThirdText().setDisabled(!thirdCanEdit);
		this.bean.getFourthText().setDisabled(!fourthCanEdit);
	}

	private void bandListbox() {
		// 奖励级别
		ListboxUtils.rendererForEdit(bean.getEncourrank(),
				NodeVoUtil.getDictionaries(UecConstants.AWARD_LEVEL));
		// 奖励档次
		ListboxUtils.rendererForEdit(bean.getGlbdef5(),
				NodeVoUtil.getDictionaries(UecConstants.AWARD_GARDE));
	}

	/**
	 * 检测填入的参数是否为空
	 */
	private String checkUacStaffData() {
		if (StrUtil.isNullOrEmpty(bean.getGlbdef1().getValue())) {
			return "填写奖励名称";
		} else if (StrUtil.isNullOrEmpty(bean.getEncourtype().getValue())) {
			return "填写奖励类型";
		} else if (StrUtil.isNullOrEmpty(bean.getEncourmatter().getValue())) {
			return "填写奖励事由";
		} else if (StrUtil.isNullOrEmpty(bean.getEncourmeas().getValue())) {
			return "填写奖励措施";
		} else if (StrUtil.isNullOrEmpty(bean.getEncourorg().getValue())) {
			return "填写奖励机构";
		} else if (StrUtil.isNullOrEmpty(bean.getEncourrank().getSelectedItem()
				.getValue())) {
			return "填写奖励级别";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef5().getSelectedItem()
				.getValue())) {
			return "填写奖励档次";
		} else if (StrUtil.isNullOrEmpty(bean.getEncourdate().getValue())) {
			return "填写奖励日期";
		}
		return null;
	}

}
